#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
火之夜工作室 Flutter 项目 lib 目录复制工具

用于复制和处理 Flutter 项目的 lib 目录文件
支持从Git仓库获取代码
"""

import os
import shutil
import tempfile
import subprocess

def clone_git_repo(git_url, branch='master'):
    """
    从Git仓库克隆代码到临时目录
    """
    try:
        # 创建临时目录
        temp_dir = tempfile.mkdtemp()
        print_colored(f"正在从Git仓库克隆代码到临时目录: {temp_dir}", "blue")
        
        # 克隆指定分支的代码
        subprocess.run(
            ['git', 'clone', '-b', branch, '--single-branch', git_url, temp_dir],
            check=True,
            capture_output=True,
            text=True
        )
        
        print_colored("Git仓库克隆成功！", "green")
        return temp_dir
    except subprocess.CalledProcessError as e:
        error_msg = str(e.stderr) if e.stderr else str(e)
        print_colored(f"Git仓库克隆失败: {error_msg}", "red")
        if os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)
        return None

from utils import print_colored

def copy_lib_directory(source_dir, target_dir, project_name,project_type, package_name, display_name, git_url='https://gitee.com/hot_night/hzy_original_project.git', branch='master'):
    """
    复制并处理lib目录文件和pubspec.yaml
    支持从本地目录或Git仓库复制
    """
    # 如果提供了git_url，从Git仓库获取代码
    if git_url:
        temp_dir = clone_git_repo(git_url, branch)
        if not temp_dir:
            return False
        source_dir = temp_dir

    try:
        # 复制pubspec.yaml
        # 读取pubspec.yaml内容
        pubspec_source = os.path.join(source_dir, 'pubspec.yaml')
        # 目标文件路径
        pubspec_target = os.path.join(target_dir, 'pubspec.yaml')
        
        if os.path.exists(pubspec_source):
            print_colored("正在复制并处理pubspec.yaml...", "blue")
            try:
                with open(pubspec_source, 'r', encoding='utf-8') as f:
                    source_content = f.read()
                
                # 提取dependencies部分（保留注释）
                dependencies_start = source_content.find('dependencies:')
                if dependencies_start == -1:
                    dependencies_content = 'dependencies:\n'
                else:
                    dependencies_end = source_content.find('\n\n', dependencies_start)
                    if dependencies_end == -1:
                        dependencies_end = len(source_content)
                    dependencies_content = source_content[dependencies_start:dependencies_end]
                
                # 读取目标文件内容（如果存在）
                target_content = ''
                if os.path.exists(pubspec_target):
                    with open(pubspec_target, 'r', encoding='utf-8') as f:
                        target_content = f.read()
                
                print_colored(target_content, "yellow")
                # 替换项目名称和描述
                # target_content = target_content.replace('hzy_original_project', project_name)
                if project_type == 'module':
                    target_content = target_content.replace('description: "A new Flutter module project."', 'description: "火之夜工作室 Flutter 脚手架"')
                else:
                    target_content = target_content.replace('description: "A new Flutter project."', 'description: "火之夜工作室 Flutter 脚手架"')
                # 添加publish_to配置防止意外发布
                if 'publish_to:' not in target_content:
                    target_content = target_content.replace(
                        'name: ' + project_name + '\n',
                        'name: ' + project_name + '\npublish_to: none\n'
                    )
                # 如果是module类型项目，保留module相关内容
                module_content = ''
                if project_type == 'module':
                    module_start = target_content.find('module:')
                    if module_start != -1:
                        module_end = target_content.find('\n\n', module_start)
                        if module_end == -1:
                            module_end = len(target_content)
                        module_content = target_content[module_start:module_end]
                
                # 合并dependencies内容（保留目标文件中的注释）
                if 'dependencies:' in target_content:
                    # 保留目标文件中dependencies之前的注释
                    target_deps_start = target_content.find('dependencies:')
                    target_comments = target_content[:target_deps_start]
                    merged_content = target_comments + dependencies_content + '\n'
                else:
                    merged_content = target_content + '\n' + dependencies_content + '\n'
                # 添加module相关内容
                merged_content += '\n' + module_content + '\n'
                with open(pubspec_target, 'w', encoding='utf-8') as f:
                    f.write(merged_content)
                    
                print_colored("pubspec.yaml处理完成！", "green")
            except Exception as e:
                print_colored(f"处理pubspec.yaml时发生错误: {str(e)}", "red")
                if git_url and os.path.exists(source_dir):
                    shutil.rmtree(source_dir)
                return False
        
        # 复制assets目录
        assets_source = os.path.join(source_dir, 'assets')
        assets_target = os.path.join(target_dir, 'assets')
        
        if os.path.exists(assets_source):
            print_colored("正在复制assets目录...", "blue")
            # 兼容Python 3.7，不使用dirs_exist_ok参数
            if os.path.exists(assets_target):
                shutil.rmtree(assets_target)
            shutil.copytree(assets_source, assets_target)
            print_colored("assets目录复制完成！", "green")
        
        # 复制lib目录
        lib_source = os.path.join(source_dir, 'lib')
        lib_target = os.path.join(target_dir, 'lib')
        
        if not os.path.exists(lib_source):
            print_colored("错误: 源lib目录不存在", "red")
            if git_url and os.path.exists(source_dir):
                shutil.rmtree(source_dir)
            return False
        
        # 确保目标lib目录存在
        os.makedirs(lib_target, exist_ok=True)
        
        # 复制lib目录
        print_colored("正在复制lib目录文件...", "blue")
        
        for root, dirs, files in os.walk(lib_source):
            # 计算目标目录路径
            rel_path = os.path.relpath(root, lib_source)
            target_root = os.path.join(lib_target, rel_path)
            
            # 创建目标目录
            os.makedirs(target_root, exist_ok=True)
            
            # 复制文件
            for file in files:
                if file.endswith('.dart'):
                    source_file = os.path.join(root, file)
                    target_file = os.path.join(target_root, file)
                    
                    # 复制文件
                    shutil.copy2(source_file, target_file)
                    
                    # 处理文件内容
                    try:
                        with open(target_file, 'r', encoding='utf-8') as f:
                            content = f.read()
                        
                        # 替换包名和项目名
                        content = content.replace('hzy_original_project', project_name)
                        content = content.replace('com.example.hzy_original_project', package_name)
                        content = content.replace('HzyOriginalProject', ''.join(word.capitalize() for word in project_name.split('_')))
                        
                        # 替换显示名称
                        content = content.replace('火之夜工作室 Flutter 通用项目框架', display_name)
                        
                        with open(target_file, 'w', encoding='utf-8') as f:
                            f.write(content)
                    except UnicodeDecodeError:
                        print_colored(f"警告: 无法处理文件 {file} 的内容", "yellow")
                        continue
        
        print_colored("lib目录复制完成！", "green")
        
        # 复制test目录
        test_source = os.path.join(source_dir, 'test')
        test_target = os.path.join(target_dir, 'test')
        
        if os.path.exists(test_source):
            print_colored("正在复制test目录...", "blue")
            # 兼容Python 3.7，不使用dirs_exist_ok参数
            if os.path.exists(test_target):
                shutil.rmtree(test_target)
            shutil.copytree(test_source, test_target)
            
            # 处理widget_test.dart文件中的import路径
            widget_test_path = os.path.join(test_target, 'widget_test.dart')
            if os.path.exists(widget_test_path):
                try:
                    with open(widget_test_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # 替换import路径
                    content = content.replace(
                        "import 'package:hzy_original_project/init/init.dart';", 
                        f"import 'package:{project_name}/init/init.dart';"
                    )
                    
                    with open(widget_test_path, 'w', encoding='utf-8') as f:
                        f.write(content)
                except Exception as e:
                    print_colored(f"警告: 处理widget_test.dart时发生错误: {str(e)}", "yellow")
            
            print_colored("test目录复制完成！", "green")
        
        # 复制.gitignore文件
        gitignore_source = os.path.join(source_dir, '.gitignore')
        gitignore_target = os.path.join(target_dir, '.gitignore')
        
        if os.path.exists(gitignore_source):
            print_colored("正在复制.gitignore文件...", "blue")
            shutil.copy2(gitignore_source, gitignore_target)
            print_colored(".gitignore文件复制完成！", "green")
        
        # 复制项目说明文档.md
        doc_source = os.path.join(source_dir, '项目说明文档.md')
        doc_target = os.path.join(target_dir, '项目说明文档.md')
        
        if os.path.exists(doc_source):
            print_colored("正在复制项目说明文档.md...", "blue")
            shutil.copy2(doc_source, doc_target)
            print_colored("项目说明文档.md复制完成！", "green")
        
        # 如果是从Git仓库克隆的，清理临时目录
        if git_url and os.path.exists(source_dir):
            shutil.rmtree(source_dir)
            print_colored("临时目录清理完成", "blue")
        
        return True
    except Exception as e:
        print_colored(f"复制过程中发生错误: {str(e)}", "red")
        # 确保清理临时目录
        if git_url and os.path.exists(source_dir):
            shutil.rmtree(source_dir)
        return False